package com.education.service.trade.controller.web;

import com.education.helper.JwtHelper;
import com.education.result.R;
import com.education.result.ResultCodeEnum;
import com.education.service.trade.entity.Order;
import com.education.service.trade.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 订单 - 前端控制器
 * Created by Lance on 2020/07/09 19:39
 */
@RestController
@Api(tags = "网站订单管理")
@RequestMapping("/web/trade/order")
public class WebOrderController {

    @Autowired
    private OrderService orderService;

    @ApiOperation("新增订单")
    @PostMapping("auth/save/{courseId}")
    public R save(@PathVariable String courseId, HttpServletRequest request) {
        // 获取用户ID
        String memberId = JwtHelper.getId(request);
        // 下单并获取订单号
        String orderId = orderService.saveOrder(courseId, memberId);
        return R.ok().data("orderId", orderId);
    }

    @ApiOperation("获取订单信息")
    @GetMapping("auth/get/{orderId}")
    public R get(@PathVariable String orderId, HttpServletRequest request) {
        String memberId = JwtHelper.getId(request);
        Order order = orderService.getByOrderId(orderId, memberId);
        return R.ok().data("order", order);
    }

    @ApiOperation( "判断课程是否购买")
    @GetMapping("auth/is-buy/{courseId}")
    public R isBuyByCourseId(@PathVariable String courseId, HttpServletRequest request) {

        String memberId = JwtHelper.getId(request);
        Boolean isBuy = orderService.isBuyByCourseId(courseId, memberId);
        return R.ok().data("isBuy", isBuy);
    }

    @ApiOperation(value = "获取当前用户订单列表")
    @GetMapping("auth/list")
    public R list(HttpServletRequest request) {
        String memberId = JwtHelper.getId(request);
        List<Order> list = orderService.selectByMemberId(memberId);
        return R.ok().data("items", list);
    }

    @ApiOperation(value = "删除订单")
    @DeleteMapping("auth/remove/{orderId}")
    public R remove(@PathVariable String orderId, HttpServletRequest request) {
        String memberId = JwtHelper.getId(request);
        boolean result = orderService.removeOrderById(orderId, memberId);
        if (result) {
            return R.ok().message("删除成功");
        } else {
            return R.error().message("数据不存在");
        }
    }

    @ApiOperation(value = "查询支付状态")
    @GetMapping("/query-pay-status/{orderNo}")
    public R queryPayStatus(@PathVariable String orderNo) {
        boolean result = orderService.queryPayStatus(orderNo);
        if (result) {   // 支付成功
            return R.ok().message("支付成功");
        }
        return R.setResult(ResultCodeEnum.PAY_RUN);//支付中
    }
}
